package com.hmdp;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;



@SpringBootTest
public class AITestDemo {
    //密钥
    public static final String AI_DEEPSEEK_KEYS = "sk-2cf104f1b8fc48719996c54943df8c08";
    //基础访问链接
    public static final String BASE_URL = "https://api.deepseek.com/v1/chat/completions";


    @Test
    public void AITest(){
        //请求体
        String requestBody = "{\"model\":\"deepseek-chat\",\"messages\":[{\"role\":\"user\",\"content\":\" \"}]}";
        //基于HttpClients方式新建post方式请求
        try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(BASE_URL);

            //设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + AI_DEEPSEEK_KEYS);

            //设置请求体
            httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));

            //发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                String responseBody = EntityUtils.toString(entity);
                //System.out.println("DeepSeek API 接口返回Json格式信息: " + responseBody);
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                JSONObject firstChoices = jsonObject.getJSONArray("choices").getJSONObject(0);
                JSONObject message = firstChoices.getJSONObject("message");
                String[] messageArray = message.toString().split(":");

//                System.out.println(message.toString());
                System.out.println("DeepSeek API 接口返回的对话信息: " + messageArray[2].substring(0, messageArray[2].length()-2));
            }
        } catch (Exception e) {
            System.err.println("请求失败" + e.getMessage());
        }


    }

}
